package com.dream.web.aop.aspectj;


import com.dream.common.utils.JsonUtils;
import com.dream.common.utils.NetWorkUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.logging.Logger;

//@Aspect
//@Component
public class AspectLogMonitor {
    private final Logger aspectLog = Logger.getLogger("aspectLog");

    /**
     * 定义切面点;不处理后置异常及前置token校验,已在其他方式处理
     */
    @Pointcut("execution(public * com.dream.web.controller..*.*(..))")
    private void webLog() {}


    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        try{
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String sb = "\n====================================================\n" +
                    "\n>>>>URL : " + request.getRequestURL().toString() +
                    "\n>>>>IP : " + NetWorkUtil.getIpAddr(request) +
                    "\n>>>>HTTP_METHOD : " + request.getMethod() +
                    "\n>>>>CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() +
                    "\n>>>>ASSIST_ARGS : " + JsonUtils.toStringPrint(joinPoint.getArgs()) +
                    "\n>>>>====================================================";
            aspectLog.info(sb);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        aspectLog.info("RESPONSE : " + JsonUtils.toStringPrint(ret));
    }





}